package com.security6.smssecurity.config;

import com.security6.smssecurity.filter.SmsCodeAuthenticationFilter;
import com.security6.smssecurity.filter.SmsCodeAuthenticationProvider;
import com.security6.smssecurity.service.impl.SmsUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @Author: wangzhen
 * @Date: 2024-08-16 12:06
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Component
public class SmsCodeAuthenticationSecurityConfig extends AbstractHttpConfigurer<SmsCodeAuthenticationSecurityConfig, HttpSecurity> {
    @Resource
    private SmsUserService smsUserService;
    @Resource
    private AuthenctiationSuccessHandler authenctiationSuccessHandler;
    @Resource
    private AuthenctiationFailHandler authenctiationFailHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenctiationSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenctiationFailHandler);

        smsCodeAuthenticationFilter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));

        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(smsUserService);

        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
